/*
Copyright 2012 Cuong Pham

This file is part of eTrack project.

eTrack is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.

eTrack is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License
along with eTrack. If not, see http://www.gnu.org/licenses/.
*/

/***********************************************************************************************
 *    Project Name: eTrack
 *    Project website: http://code.google.com/p/etrack/
 * *********************************************************************************************/


#include <XBee.h>

#define RESET 100 
#define BRCAST 101 
#define RSSI 102 

#define MY_ID 16 

XBee xbee = XBee();

uint8_t payload[] = { 0, 0, 0 };

// 16-bit addressing: Enter address of remote XBee, typically the coordinator
Tx16Request tx16 = Tx16Request(0x0000, payload, sizeof(payload));

// 64-bit addressing: This is the SH + SL address of remote XBee
XBeeAddress64 addr64 = XBeeAddress64(0x00000000, 0x0000FFFF);
// unless you have MY on the receiving radio set to FFFF, this will be received as a RX16 packet
Tx64Request tx64 = Tx64Request(addr64, payload, sizeof(payload));

TxStatusResponse txStatus = TxStatusResponse();


XBeeResponse response = XBeeResponse();
// create reusable response objects for responses we expect to handle 
Rx16Response rx16 = Rx16Response();
Rx64Response rx64 = Rx64Response();


int statusLed = 13;
int errorLed = 13;
uint8_t rssi = 0;
uint8_t serial = 0;
boolean refresh = false;


void flashLed(int pin, int times, int wait) {
    
    for (int i = 0; i < times; i++) {
      digitalWrite(pin, HIGH);
      delay(wait);
      digitalWrite(pin, LOW);
      
      if (i + 1 < times) {
        delay(wait);
      }
    }
}

void setup() {
  pinMode(statusLed, OUTPUT);  
  xbee.begin(9600);
}

void loop() {
    xbee.readPacket();
    if (xbee.getResponse().isAvailable()) {
      // got something
      if (xbee.getResponse().getApiId() == RX_16_RESPONSE || xbee.getResponse().getApiId() == RX_64_RESPONSE) {
        // got a rx packet
      
        if (xbee.getResponse().getApiId() == RX_16_RESPONSE) {
                xbee.getResponse().getRx16Response(rx16);
                if (rx16.getData(0)==BRCAST){
                  refresh = true;
              serial = rx16.getData(1);
                  rssi = rx16.getRssi();
                  sendMsg16(RSSI,serial,rssi);
                  //Serial.println(rssi);
                }
        } else {
                xbee.getResponse().getRx64Response(rx64);
                if (rx64.getData(0)==BRCAST){
                  refresh = true;
              serial = rx64.getData(1);
                  rssi = rx64.getRssi();
                  sendMsg16(RSSI,serial,rssi);
                  
                }
         }
        
        // TODO check option, rssi bytes    
        flashLed(statusLed, 1, 100);
        
      } else {
          // not something we were expecting
        flashLed(errorLed, 3, 25);    
      }
    } else if (xbee.getResponse().isError()) {
        flashLed(errorLed, 5, 25);    
    }
}

void sendMsg16(int type, int _serial, int _rssi) { 
  delay(50*MY_ID);  
  payload[0]=type;
  payload[1]=_serial;
  payload[2]=_rssi;
  
  xbee.send(tx16);
  
  // flash TX indicator
  flashLed(statusLed, 1, 100);
  refresh = false;

  // after sending a tx request, we expect a status response
  // wait up to 5 seconds for the status response
  if (xbee.readPacket(1000)) {
    // got a response!

    // should be a znet tx status                
    if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
      xbee.getResponse().getZBTxStatusResponse(txStatus);
            
      // get the delivery status, the fifth byte
      if (txStatus.getStatus() == SUCCESS) {
        // success.  time to celebrate
      } else {
          // the remote XBee did not receive our packet. is it powered on?
          if (!refresh) 
            sendMsg16(type, _serial, _rssi);
        }
      }      
    } else if (xbee.getResponse().isError()) {
        if (!refresh)
          sendMsg16(type, _serial, _rssi);
    } else {
        // local XBee did not provide a timely TX Status Response.  Radio is not configured properly or connected
        if (!refresh)  
          sendMsg16(type, _serial, _rssi);
    }    
    delay(50);  
}




